import qrcode
from PIL import ImageDraw, ImageFont
import os


class QRCodeGenerator:
    def __init__(self, version=1, error_correction=qrcode.constants.ERROR_CORRECT_L,
                 box_size=20, border=5, font_size=20, fill_color=(0, 0, 0), back_color=(255, 255, 255)):
        self.qr = qrcode.QRCode(version=version, error_correction=error_correction, box_size=box_size, border=border)
        self.left = ""
        self.bottom = ""
        self.font_size = font_size
        self.fill_color = fill_color
        self.back_color = back_color

    def set_data(self, **kwargs):
        self.bottom = kwargs.get('bottom', '')
        self.left = kwargs.get('left', '')
        self.qr.clear()
        # 以左上角绘制
        self.qr.add_data(self.left)
        self.qr.make(fit=True)

    def generate_qr_code(self):
        img = self.qr.make_image(fill_color=self.fill_color, back_color=self.back_color)
        draw = ImageDraw.Draw(img)

        # Load the font file or use the default font if not found
        font_path = "./MSYH.TTC"
        if os.path.isfile(font_path):
            font = ImageFont.truetype(font_path, size=self.font_size)
        else:
            font = ImageFont.load_default()

        bbox = draw.textbbox((0, 0), self.bottom, font=font)
        textwidth = bbox[2] - bbox[0]
        textheight = bbox[3] - bbox[1]
        width, height = img.size

        draw.text(((width - textwidth) / 2, height - textheight - 10), self.bottom, font=font, fill=(0, 0, 0, 0))
        draw.text((0, 0), self.left, font=font, fill=(0, 0, 0, 0))
        return img

    def save_qr_code(self, filename):
        try:
            qr_code_image = self.generate_qr_code()
            qr_code_image.save(filename)
            print(f"QR code saved as {filename}")
        except Exception as e:
            print(f"Error saving QR code: {e}")


if __name__ == "__main__":
    # 创建QRCodeGenerator实例
    qr_generator = QRCodeGenerator()

    # 设置二维码数据
    qr_generator.set_data(bottom="test", left="test")

    # 生成并保存二维码图像
    qr_generator.save_qr_code("example_qr_code.png")
